import { BaseSystem } from '../base';
import { EVENTS, type IEventBus } from '../../events';
import type {
  CultivationSkillModel,
  PlayerProgressModel,
  RealmModel,
} from '../../model';
import type { PlayerStateSystem } from '../player-state';
import { MODEL_NAME } from '../../constants/model-names';

export class PlayerProgressSystem extends BaseSystem {
  private bus: IEventBus;
  private playerStateSystem: PlayerStateSystem;
  /** 多少秒更新一次 */
  private updateInterval = 60;
  /** 已经进行了多少秒 */
  private passedTime = 0;

  constructor(bus: IEventBus, playerStateSystem: PlayerStateSystem) {
    super();
    this.bus = bus;
    this.playerStateSystem = playerStateSystem;

    this.bus.on(EVENTS.PLAYER_PROGRESS_SET_INIT_SPIRITUAL_ROOT, (flag) => {
      const playerProgressModel =
        this.playerStateSystem.getModel<PlayerProgressModel>(
          MODEL_NAME.PLAYER_PROGRESS
        );
      if (!playerProgressModel) return;
      playerProgressModel.setInitedSpiritualRoot(flag);
    });
  }

  public init(): void {
    const playerProgressModel =
      this.playerStateSystem.getModel<PlayerProgressModel>(
        MODEL_NAME.PLAYER_PROGRESS
      );
    const cultivationSkillModel =
      this.playerStateSystem.getModel<CultivationSkillModel>(
        MODEL_NAME.CULTIVATION_SKILL
      );
    const realmModel = this.playerStateSystem.getModel<RealmModel>(
      MODEL_NAME.REALM
    );
    if (!playerProgressModel || !cultivationSkillModel || !realmModel) return;
    playerProgressModel.setRealm(realmModel.getRealm());
    cultivationSkillModel.getPlayerSkillsInfo().forEach((skillItem) => {
      playerProgressModel.addLearnedCultivationSkill(skillItem.skill.skillId);
    });
  }

  public update(dt: number): void {
    this.passedTime += dt;
    if (this.passedTime >= this.updateInterval) {
      this.bus.emit(EVENTS.PLAYER_PROGRESS_STATE_UPDATE);
      this.passedTime -= this.updateInterval;
    }
  }
}
